package com.java.zhuiyun.api.playerinformation.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.java.zhuiyun.api.houserank.entity.HouseRank;
import com.java.zhuiyun.api.playerinformation.entity.PlayerInformation;
import com.java.zhuiyun.api.playerinformation.mapper.PlayerInformationMapper;
import com.java.zhuiyun.api.playerinformation.model.AppUser;
import com.java.zhuiyun.api.playerinformation.service.PlayerInformationService;
import com.java.zhuiyun.api.propmgt.entity.PropCenter;
import com.java.zhuiyun.api.propmgt.entity.PropMgt;
import com.java.zhuiyun.api.propmgt.mapper.PropMgtMapper;
import com.java.zhuiyun.api.rolerank.entity.RoleRank;
import com.java.zhuiyun.api.userAchievement.mapper.UserAchievementMapper;
import com.java.zhuiyun.common.errorCode.EmErrorCode;
import com.java.zhuiyun.common.response.CommonResult;
import com.java.zhuiyun.util.ObjectUtils;
import com.java.zhuiyun.util.WXUtils;
import com.java.zhuiyun.util.pageUtil.MybatisPageHelper;
import com.java.zhuiyun.util.pageUtil.PageRequest;
import com.java.zhuiyun.util.pageUtil.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * (PlayerInformation)表服务实现类
 *
 * @author makejava
 * @since 2023-09-14 10:35:44
 */
@Service
public class PlayerInformationServiceImpl implements PlayerInformationService {
    @Autowired
    private PlayerInformationMapper playerInformationMapper;

    @Autowired
    private PropMgtMapper propMgtMapper;

    @Autowired
    private UserAchievementMapper userAchievementMapper;

    /*
    * @Author wuwan
    * @Description 查询所有已注册用户(全查)
    * @Date 2023/9/18 11:30
    * @Return
    * @param null
    */
    @Override
    public CommonResult selectPlayerInformation(PageRequest pageRequest,String name) {
        MybatisPageHelper.startPage(pageRequest);
        PageResult pageResult = MybatisPageHelper.getPageResult(playerInformationMapper.selectPlayerInformation(name));
        return CommonResult.ok(pageResult);
    }
    /*
    * @Author wuwan
    * @Description 微信用户登录
    * @Date 2023/9/18 11:30
    * @Return
    * @param null
    */
    @Override
    public CommonResult getOpenid(@RequestBody AppUser code) {
        JSONObject jsonObject = WXUtils.getOpenid(code.getCode());
        if (ObjectUtils.isNotEmpty(jsonObject)) {
            Object openid = jsonObject.get("openid");
            if(openid==null||openid==""){
                return CommonResult.error("授权失败");
            }
            //查询数据库中有没有这个用户
            AppUser appUser = playerInformationMapper.selectByUserId((String) openid);
            if (appUser != null) {
                // 有此用户则将此用户的信息返回给前端 进行登录
                return CommonResult.ok(appUser);
            }
            // 未拥有此用户则进行注册  在将用户信息返回给前端进行登录
            PlayerInformation playerInformation = new PlayerInformation();
            playerInformation.setOpenid((String) openid);
            playerInformation.setUserName(code.getUserName());
            playerInformation.setUserAvatar(code.getUserAvatar());
            playerInformation.setCreateTime(new Date());
            playerInformation.setUpdateTime(new Date());
            Integer integer = playerInformationMapper.registerUser(playerInformation); // todo 有bug 下午改
            // 判断是否注册成功
            if (integer >= 1) {
                //注册成功后 将添加的数据查询出来 用来返回给前端进行登录
                AppUser appUsers = playerInformationMapper.selectByUserId((String) openid);
                // 在道具表中给新用户添加他的道具信息
                PropCenter propCenter = new PropCenter();
                List<PropMgt> propMgts = playerInformationMapper.selectPropId();
                for (int i = 0; i < propMgts.size(); i++) {
                    PropMgt propMgt = propMgts.get(i);
                    propCenter.setUserId(appUsers.getId());
                    propCenter.setPropId(propMgt.getId());
                    propCenter.setCreateTime(new Date());
                    propCenter.setUpdateTime(new Date());
                    propMgtMapper.addPropCenter(propCenter);
                }
                //将数据返回给前端
                appUsers.setId(null);
                return CommonResult.ok(appUsers);
            }
            return CommonResult.error(EmErrorCode.ID_NOT_OBJECT);
        } else {
            return CommonResult.error(EmErrorCode.ID_NOT_OBJECT);
        }
    }
    /*
     * @Author wuwan
     * @Description 进入页面刷新最后登录时间
     * @Date 2023/9/18 19:54
     * @Return
     * @param null
     */
    @Override
    public CommonResult uploginTime(String openid) {
        PlayerInformation playerInformation = new PlayerInformation();
        playerInformation.setOpenid(openid);
        playerInformation.setLoginTime(new Date());
        Integer integer = playerInformationMapper.uploginTime(playerInformation);
        if (integer >= 1){
            return CommonResult.ok("成功");
        }
        return CommonResult.error("失败");
    }


    /*
     * @Author WX
     * @Description 冒险关卡次数修改方法
     * @Date 2023/9/18 9:49
     * @Return
     * @param null
     */
    @Override
    public int updateNumberOfModifications() {
        return playerInformationMapper.updateNumberOfModifications();
    }
    /*
     * @Author wuwan
     * @Description 用户升级 (包含经验添加 和 积分添加)
     * @Date 2023/9/26 10:03
     * @Return
     */
    @Override
    public CommonResult upPlayerLevel(PlayerInformation playerInformation) {
        // 判断是否获得积分 获得积分则添加积分
        if (playerInformation.getCurrentPlayerScore() != null) {
            upCatchHousePlayerLevel(playerInformation);
        }
        // 判断是否获得经验 获得经验则添加经验
        if (playerInformation.getCurrentPlayerExperience() != null) {
            upCatchPlayerLevel(playerInformation);
        }
        if (playerInformation.getCurrentPlayerExperience() != null) {
            String openid = playerInformation.getOpenid();
            // 查询出用户的等级和经验
            PlayerInformation playerInformation2 = playerInformationMapper.selectPlayerLevel(openid);
            // 当前等级
            Integer currentPlayerLevel = playerInformation2.getCurrentPlayerLevel();
            // 当前经验数
            Integer currentPlayerExperience = playerInformation2.getCurrentPlayerExperience();
            // 判断是否拥有经验
            while (currentPlayerExperience >= 0) {
                // 查询当前等级的升级所需经验
                RoleRank playerLevel = playerInformationMapper.getPlayerLevel(currentPlayerLevel);

                // 判断用户是否可以升级
                if (currentPlayerExperience >= playerLevel.getRoleNeedLevel()) {
                    // 升级后的等级
                    Integer nextLevel = currentPlayerLevel + 1;
                    // 判断是不是到达最高等级
                    RoleRank nextLevelInfo = playerInformationMapper.getPlayerLevel(nextLevel);
                    if (nextLevelInfo == null) {
                        return CommonResult.error("已达到最高等级");
                    }
                    // 从新赋值升级后的等级
                    currentPlayerLevel = nextLevel;
                    // 减去已经消耗的经验数量
                    currentPlayerExperience -= playerLevel.getRoleNeedLevel();
                    // 将数据存储 升级sql时使用
                    playerInformation.setCurrentPlayerLevel(currentPlayerLevel);
                    playerInformation.setCurrentPlayerExperience(currentPlayerExperience);
                    // 等级添加
                    Integer integer = playerInformationMapper.upPlayerLevel(playerInformation);

                    if (integer >= 1) {
                        // 查询当前等级
                        PlayerInformation playerInformation1 = playerInformationMapper.selectPlayerLevel(openid);
                        // 角色等级大于等于10级解锁成就
                        if (playerInformation1.getCurrentPlayerLevel() >= 10) {
                            userAchievementMapper.updateBringHomeTheBacon(playerInformation1.getId());
                        }
                    } else {
                        return CommonResult.ok("升级失败");
                    }
                } else {
                    break;
                }
            }
        }
            return CommonResult.ok("经验不足请继续加油!");
        }

    /*
     * @Author wuwan
     * @Description 房屋升级规则
     * @Date 2023/9/26 14:56
     * @Return
     */
    @Override
    public CommonResult upPlayerHouseLevel(PlayerInformation playerInformation) {
        // 获取当前房屋等级和当前积分
        PlayerInformation playerInformation2 = playerInformationMapper.selectPlayerHouseLevel(playerInformation.getOpenid());
        // 获取升级所需积分
        HouseRank playerHouseLevel = playerInformationMapper.getPlayerHouseLevel(playerInformation2.getCurrentPlayerHouseLevel());
        // 判断用户是否可以升级
        if (playerInformation2.getCurrentPlayerScore() >= playerHouseLevel.getHouseNeedLevel()){
            // 升级后的等级
            Integer p = playerInformation2.getCurrentPlayerHouseLevel()+1;
            // 判断用户是否到达目前最高等级
            HouseRank playerHouseLevel1 = playerInformationMapper.getPlayerHouseLevel(p);
            if (playerHouseLevel1 == null){
                return CommonResult.error("已达到最高等级");
            }
            // 进行升级
            playerInformation.setCurrentPlayerHouseLevel(p);
            playerInformation.setCurrentPlayerScore(playerInformation2.getCurrentPlayerScore() - playerHouseLevel.getHouseNeedLevel());
            Integer integer = playerInformationMapper.upPlayerHouseLevel(playerInformation);
            if (integer >= 1){
                PlayerInformation playerInformation1 = playerInformationMapper.selectPlayerHouseLevel(playerInformation.getOpenid());
                if (playerInformation1.getCurrentPlayerHouseLevel()>=10){
                    userAchievementMapper.updateFairyland(playerInformation1.getId());
                }

                return CommonResult.ok("恭喜升级");
            }
            return CommonResult.ok("升级失败");
        }
        return CommonResult.ok("经验不足请继续加油!");
    }

    /**
    * @Author 杨友朋
    * @Description TODO 单查
    * @Date 2023/9/27 15:52
    * @Return
    */
    @Override
    public AppUser selectByUserId(String openId) {
        AppUser appUser = playerInformationMapper.selectByUserId(openId);
        return appUser;
    }

    /*
     * @Author WX
     * @Description 根据openid查询出用户的信息数量
     * @Date 2023/9/27 9:38
     * @Return
     * @param openid
     */
    @Override
    public CommonResult queryByUser(String openid) {
        PlayerInformation playerInformation = playerInformationMapper.queryByUser(openid);
        return  CommonResult.ok(playerInformation);
    }

    /*
     * @Author wuwan
     * @Description 修改冒险次数
     * @Date 2023/9/27 9:32
     * @Return
     */
    @Override
    public int queryByOpenId(String openid) {
        return playerInformationMapper.queryByOpenId(openid);
    }

    /*
     * @Author WX
     * @Description 修改冒险通关次数
     * @Date 2023/10/8 9:39
     * @Return
     * @param null
     */
    @Override
    public int updateAdventureIdNumber(String openid) {
        return playerInformationMapper.updateAdventureIdNumber(openid);
    }
    /*
    * @Author wuwan
    * @Description 下一关（成语接龙）
    * @Date 2023/10/12 8:40
    * @Return
    */
    @Override
    public CommonResult nextLevel(AppUser appUser) {
        Integer i = playerInformationMapper.nextLevel(appUser);
        if (i > 0) {
            return CommonResult.ok();
        }
        return CommonResult.error();
    }
    /*
     * @Author WX
     * @Description 冒险通关成功后操作
     * @Date 2023/10/9 10:16
     * @Return
     * @param openid
     */
    @Override
    public PropMgt passingLevelSuccessful(String openid) {
        AppUser appUser = playerInformationMapper.selectByUserId(openid);
        int userId = appUser.getId();
        // 添加角色积分
        int i = playerInformationMapper.addPoints(openid);
        // 从道具id中随机取一个
        int propId = (int)(Math.random() * 2) + 1;
        int j =propMgtMapper.addPropCenterByOpenid(userId,propId);
        PropMgt propMgt = propMgtMapper.selectPropNameById(propId);
        return propMgt;
    }

    /*
     * @Author WX
     * @Description 冒险通一个小关卡操作
     * @Date 2023/10/17 8:58
     * @Return
     * @param id
     */
    @Override
    public CommonResult adventurePassOneLevelOperation(int id) {
        // 添加答对题和词语数量
        int i = playerInformationMapper.adventurePassOneLevelOperation(id);
        if (i>0){
            // 通过id查询数据
            PlayerInformation playerInformation = playerInformationMapper.selectPlayerInformationById(id);
            // 判断答题数是否达标
            if (playerInformation.getCorrectlyAnsweredQuestions() >= 150){
                // 达标就调用修改方法
                int a = userAchievementMapper.updateBeWealthyInKnowledge(id);
            }
            // 判断填对词数是否大于6666字
            if (playerInformation.getCorrectlyAnsweredWord() >= 6666){
                // 判断是否大于23456字
                if (playerInformation.getCorrectlyAnsweredWord() >= 23456){
                    int b =userAchievementMapper.updateShakeAndBreak(id);
                }else {
                    int c = userAchievementMapper.updateBeLearnedInBooks(id);
                }
            }
            return CommonResult.ok(EmErrorCode.UPDATE_OK);
        }else {
            return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
        }
    }
    /**
    * @Author MJL
    * @Description todo 看图猜成语关卡机制
    * @Date 2023/10/19 10:00
    * @Return  * @param null
    */
    @Override
    public CommonResult pictureLevelUp(PlayerInformation playerInformation) {
        Integer integer = playerInformationMapper.picturePlayerLevel(playerInformation);
        return CommonResult.ok("!");
    }

    /**
     * @Author 杨友朋
     * @Description TODO 成语接龙通一个小关卡操作
     * @Date 2023/10/20 9:38
     * @Return CommonResult
     * @param id,correctlyAnsweredQuestions,correctlyAnsweredWord
     */
    @Override
    public CommonResult idiomGOGOGO(int id, Integer correctlyAnsweredQuestions, Integer correctlyAnsweredWord) {
        int i = playerInformationMapper.idiomGOGOGO(id,correctlyAnsweredQuestions,correctlyAnsweredWord);
        if (i>0){
            // 通过id查询数据
            PlayerInformation playerInformation = playerInformationMapper.selectPlayerInformationById(id);
            if (playerInformation.getCorrectlyAnsweredQuestions() >= 150){
                int a = userAchievementMapper.updateBeWealthyInKnowledge(id);
            }
            if (playerInformation.getCorrectlyAnsweredWord() >= 6666){
                if (playerInformation.getCorrectlyAnsweredWord() >= 23456){
                    int b =userAchievementMapper.updateShakeAndBreak(id);
                }else {
                    int c = userAchievementMapper.updateBeLearnedInBooks(id);
                }
            }
            return CommonResult.ok(EmErrorCode.UPDATE_OK);
        }else {
            return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
        }
    }

    /*
     * @Author wuwan
     * @Description 给用户添加积分
     * @Date 2023/9/26 14:54
     * @Return
     */
    public CommonResult upCatchHousePlayerLevel(PlayerInformation playerInformation){
        // 获取当前房屋等级和当前积分
        PlayerInformation playerInformation2 = playerInformationMapper.selectPlayerHouseLevel(playerInformation.getOpenid());
        playerInformation.setCurrentPlayerScore(playerInformation2.getCurrentPlayerScore() + playerInformation.getCurrentPlayerScore());
        Integer integer = playerInformationMapper.upCatchHousePlayerLevel(playerInformation);
        if (integer >= 1){
            return CommonResult.ok("积分添加成功");
        }
        return CommonResult.error("积分添加失败");
    }
    /*
     * @Author wuwan
     * @Description 给用户添加经验
     * @Date 2023/9/26 14:54
     * @Return
     */
    public CommonResult upCatchPlayerLevel(PlayerInformation playerInformation){
        // 查询用户的等级和已有经验
        PlayerInformation playerInformation1 = playerInformationMapper.selectPlayerLevel(playerInformation.getOpenid());
        // 计算出过关后的经验该用户的经验数
        Integer i = playerInformation1.getCurrentPlayerExperience() + playerInformation.getCurrentPlayerExperience();
        playerInformation.setCurrentPlayerExperience(i);
        Integer integer = playerInformationMapper.upCatchPlayerLevel(playerInformation);
        if (integer >= 1){
            return CommonResult.ok("经验添加成功");
        }
        return CommonResult.error("经验添加失败");
    }
}
